<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use app\common\exception\UploadException;
use app\common\library\Upload;
use getID3;
use think\Db;

/**
 * 歌曲接口
 */
class Recommend extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function songs(){
        $uid = $this->request->get('uid', '');
        $limit = $this->request->get('limit', 10, 'int');
        
        // 从数据库获取推荐歌曲
        $songs = \think\Db::query("
            SELECT 
                s.id,
                s.name,
                s.album_id as album_id,
                s.album_name,
                s.album_image as picUrl
            FROM 
                mu_song s
            ORDER BY 
                s.weigh DESC, s.createtime DESC
            LIMIT :limit
        ", ['limit' => $limit]);
        
        $dailySongs = [];
        $recommendReasons = [];
        
        // 处理每首歌曲的数据
        foreach ($songs as $song) {
            // 获取歌曲的艺术家信息
            $artists = \think\Db::query("
                SELECT 
                    a.artist_id as id,
                    a.name
                FROM 
                    mu_song_artist sa
                JOIN 
                    mu_artist a ON sa.artist_id = a.id
                WHERE 
                    sa.song_id = :song_id
            ", ['song_id' => $song['id']]);
            
            // 构建歌曲数据
            // 如果专辑信息不存在，则使用歌手信息代替
            $albumId = !empty($song['album_id']) ? $song['album_id'] : '0';
            $albumName = !empty($song['album_name']) ? $song['album_name'] : $song['name'];
            
            // 获取歌手头像作为备选
            $artistAvatar = '';
            // 检查 $artists 数组是否非空
            if (empty($song['picUrl']) && !empty($artists) && isset($artists[0])) {
                $artistInfo = \think\Db::query("
                    SELECT avatar FROM mu_artist WHERE artist_id = :artist_id LIMIT 1
                ", ['artist_id' => $artists[0]['id']]);
                
                if (!empty($artistInfo) && isset($artistInfo[0]['avatar'])) {
                    $artistAvatar = $artistInfo[0]['avatar'];
                }
            }
            
            // 如果有歌手信息，则可以使用歌手信息替代专辑信息
            if (!empty($artists) && isset($artists[0])) {
                $albumId = !empty($song['album_id']) ? $song['album_id'] : $artists[0]['id'];
                $albumName = !empty($song['album_name']) ? $song['album_name'] : $artists[0]['name'];
            }
            
            $albumPicUrl = !empty($song['picUrl']) ? $song['picUrl'] : $artistAvatar;
            
            $songData = [
                'id' => $song['id'],
                'name' => $song['name'],
                'al' => [
                    'id' => $albumId,
                    'name' => $albumName,
                    'picUrl' => cdnurl($albumPicUrl, true)
                ],
                'ar' => $artists
            ];
            
            $dailySongs[] = $songData;
            
            // 生成推荐原因
            $reason = '';
            // 随机选择推荐原因类型
            $reasonType = rand(0, 2);
            switch ($reasonType) {
                case 0:
                    $reason = '根据你的听歌喜好推荐';
                    break;
                case 1:
                    $reason = '近期热门单曲';
                    break;
                case 2:
                    $reason = '你可能喜欢的音乐风格';
                    break;
            }
            
            $recommendReasons[] = [
                'songId' => $song['id'],
                'reason' => $reason
            ];
        }
        
        // 返回数据
        $this->success('请求成功', [
            'dailySongs' => $dailySongs,
            'recommendReasons' => $recommendReasons
        ]);
    }

    public function resource(){
        $uid = $this->auth->id;
        
        // 获取推荐歌单
        $playlists = \think\Db::query("
            SELECT 
                p.playlist_id as id,
                1 as type,
                p.name,
                p.cover_image as picUrl,
                p.createtime * 1000 as createTime,
                p.user_id as userId,
                (SELECT COUNT(*) FROM mu_playlist_song ps WHERE ps.playlist_id = p.playlist_id) as trackCount
            FROM 
                mu_playlist p
            ORDER BY 
                p.createtime DESC
            LIMIT 10
        ");
        
        // 处理每个歌单的数据
        foreach ($playlists as &$playlist) {
            // 获取创建者信息
            $creator = Db::name('user')->where('id', $playlist['userId'])->find();
            
            // 如果找不到创建者，使用默认值
            if (empty($creator)) {
                $playlist['creator'] = [
                    'userId' => $playlist['userId'],
                    'nickname' => '未知用户'
                ];
            } else {
                $playlist['creator'] = $creator;
            }
            
            // 生成推荐原因
            $songs = \think\Db::query("
                SELECT 
                    s.name
                FROM 
                    mu_playlist_song ps
                JOIN 
                    mu_song s ON ps.song_id = s.song_id
                WHERE 
                    ps.playlist_id = :playlist_id
                LIMIT 1
            ", ['playlist_id' => $playlist['id']]);
            
            if (!empty($songs)) {
                $playlist['copywriter'] = '根据你喜欢的单曲《' . $songs[0]['name'] . '》推荐';
            } else {
                $playlist['copywriter'] = '为你精选推荐';
            }
            
            // 添加算法标记
            $playlist['alg'] = 'itembased';
            
            // 确保picUrl是完整URL
            if (!empty($playlist['picUrl'])) {
                $playlist['picUrl'] = cdnurl($playlist['picUrl'], true);
            }
        }
        
        // 返回符合要求的格式
        $this->success('', [
            'code' => 200,
            'featureFirst' => true,
            'haveRcmdSongs' => true,
            'recommend' => $playlists
        ]);
    }

}